package cn.wp.pet.controller;

import cn.wp.basic.util.AjaxResult;
import cn.wp.basic.util.PageList;
import cn.wp.org.domain.Employee;
import cn.wp.org.service.IEmployeeService;
import cn.wp.pet.domain.Pet;
import cn.wp.pet.domain.SearchMasterMsg;
import cn.wp.pet.query.PetQuery;
import cn.wp.pet.query.SearchMasterMsgQuery;
import cn.wp.pet.service.ISearchMasterMsgService;
import cn.wp.user.domain.LoginInfo;
import cn.wp.user.domain.User;
import cn.wp.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/searchMasterMsg")
public class SearchMasterMsgController {
    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private IEmployeeService employeeService;

    @PostMapping("/publish")
    private AjaxResult publish(@RequestBody SearchMasterMsg searchMasterMsg, HttpServletRequest request){
        try {
            // 获取token
            String token = request.getHeader("TOKEN");
            LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
            System.out.println(loginInfo.getId());
            // 根据id 查询用户
            User user =  userService.loadByLoginInfoId(loginInfo.getId());
            // 添加 发布用户
            searchMasterMsg.setUser_id(user.getId());
            searchMasterMsgService.publish(searchMasterMsg);
            return new AjaxResult();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }
    }

    @PostMapping
    public PageList<SearchMasterMsg> queryPage(@RequestBody SearchMasterMsgQuery searchMasterMsgQuery, HttpServletRequest request){
        // 获取token
        String token = request.getHeader("TOKEN");
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        System.out.println(loginInfo.getId());
        // 根据id 查询用户
        Employee employee = employeeService.loadByLoginInfoId(loginInfo.getId());
        searchMasterMsgQuery.setShopId(employee.getShop_id());
        return searchMasterMsgService.queryPage(searchMasterMsgQuery);
    }

    @GetMapping("/changeState/{id}")
    public AjaxResult changeState(@PathVariable("id") Long id){
        try {
            System.out.println(id);
            searchMasterMsgService.changeState(id);
            return new AjaxResult();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("更改失败！");
        }
    }
}
